package com.example.tellwin.mine;

import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.apkfuns.logutils.LogUtils;
import com.example.tellwin.AppHelper;
import com.example.tellwin.CallService;
import com.example.tellwin.MainActivity;
import com.example.tellwin.MainApplication;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseFragment;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.MineEvent;
import com.example.tellwin.event.WebSocketEvent;
import com.example.tellwin.mine.act.ApplyResultActivity;
import com.example.tellwin.mine.act.CreditsExchangeActivity;
import com.example.tellwin.mine.act.FeeDescriptionActivity;
import com.example.tellwin.mine.act.LoginRegisterActivity;
import com.example.tellwin.mine.act.MineAttentionActivity;
import com.example.tellwin.mine.act.MineDetailActivity;
import com.example.tellwin.mine.act.OrderListActivity;
import com.example.tellwin.mine.act.SettingActivity;
import com.example.tellwin.mine.act.ShareRecordActivity;
import com.example.tellwin.mine.act.WalletActivity;
import com.example.tellwin.mine.bean.UserContentBean;
import com.example.tellwin.mine.bean.UserInfo;
import com.example.tellwin.mine.contract.MineContract;
import com.example.tellwin.mine.presenter.MinePresenter;
import com.example.tellwin.model.TRTCCalling;
import com.example.tellwin.model.impl.TRTCCallingImpl;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.GlideUtils;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.ShareDialog;
import com.example.tellwin.view.StatusBarHeightView;
import com.tencent.imsdk.v2.V2TIMManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 *
 */
public class MineFragment extends CpBaseFragment implements MineContract.View {


    @BindView(R.id.statusbar_view)
    StatusBarHeightView statusbarView;
    @BindView(R.id.mine_head_iv)
    ImageView mineHeadIv;
    @BindView(R.id.mine_head_ll)
    RelativeLayout mineHeadLl;
    @BindView(R.id.mine_name_tv)
    TextView mineNameTv;
    @BindView(R.id.mine_logout_iv)
    ImageView mineLogoutIv;
    @BindView(R.id.mine_edit_iv)
    ImageView mineEditIv;
    @BindView(R.id.brief_introduction_tv)
    TextView briefIntroductionTv;
    @BindView(R.id.member_tv)
    TextView memberTv;
    @BindView(R.id.member_ll)
    LinearLayout memberLl;
    @BindView(R.id.score_tv)
    TextView scoreTv;
    @BindView(R.id.score_ll)
    LinearLayout scoreLl;
    @BindView(R.id.shu_xiu_tv)
    TextView shuXiuTv;
    @BindView(R.id.fee_description_tv)
    TextView feeDescriptionTv;
    @BindView(R.id.mine_order_tv)
    TextView mineOrderTv;
    @BindView(R.id.mine_attention_tv)
    TextView mineAttentionTv;
    @BindView(R.id.mine_service_tel_tv)
    TextView mineServiceTelTv;
    @BindView(R.id.mine_setting_tv)
    TextView mineSettingTv;
    @BindView(R.id.mine_banner1_iv)
    ImageView mineBanner1Iv;
    @BindView(R.id.mine_banner2_iv)
    ImageView mineBanner2Iv;
    @BindView(R.id.cut_iv)
    ImageView cutIv;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.invitation_code_tv)
    TextView invitationCodeTv;

    private Unbinder unbinder;

    @Inject
    MinePresenter mPresenter;

    UserContentBean userContentBean;

    @Override
    public View onCreateRootView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView(view);
        initEvent();
        initData();
        return view;
    }

    private void initView(View view) {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);
    }

    int position = 0;

    private void initEvent() {
        mineAttentionTv.setOnClickListener(v -> {
            startActivity(MineAttentionActivity.class);
        });
        mineOrderTv.setOnClickListener(v -> {
            startActivity(OrderListActivity.class);
        });
        mineEditIv.setOnClickListener(v -> {
            if (userContentBean == null) {
                ToastUtil.show(getActivity(), "获取用户信息失败");
                return;
            }
            Intent intent = new Intent(getActivity(), MineDetailActivity.class);
            intent.putExtra(Common.USERINFO, userContentBean);
            startActivityForResult(intent, Common.MineDetailRequestCode);
        });
        mineBanner1Iv.setOnClickListener(v -> {
            mPresenter.getUserInfo(1);
        });
        mineBanner2Iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareDialog shareDialog = new ShareDialog(getActivity(), 4, AppHelper.getInstance().getUserInfo().getIdentityCode(), AppHelper.getInstance().getUserInfo().getIdentityCode());
                shareDialog.show();
            }
        });
        shuXiuTv.setOnClickListener(v -> {
            if (userContentBean == null) {
                ToastUtil.show(getActivity(), "获取用户信息失败");
                return;
            }
            Intent intent = new Intent(getActivity(), WalletActivity.class);
            intent.putExtra(Common.USERINFO, userContentBean.getUserInfo());
            startActivity(intent);
        });
        scoreLl.setOnClickListener(v -> {
            startActivity(CreditsExchangeActivity.class);
        });
        memberTv.setOnClickListener(v -> {
            //startActivity(ShareRecordActivity.class);\
            /*MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            AssetFileDescriptor file = null;
            AssetManager assetManager = getContext().getAssets();
            try {
                file = assetManager.openFd("5363.mp3");
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
                mediaPlayer.start();
                file.close();
                assetManager.close();
            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.e(e);
            }*/
        });
        feeDescriptionTv.setOnClickListener(v -> {
            startActivity(FeeDescriptionActivity.class);
        });
        mineLogoutIv.setOnClickListener(v -> {
            AppHelper.getInstance().clearUser(getActivity());
            AppHelper.getInstance().setUserInfo(null);
            Intent intent = new Intent(getActivity(), LoginRegisterActivity.class);
            startActivity(intent);
            getActivity().finish();
            CallService.stop(getContext());
        });
        cutIv.setOnClickListener(v -> {
            if (MainApplication.Identity.equals(Common.NORMAL)) {
                mPresenter.switchIdentity(1);
            } else {
                mPresenter.switchIdentity(0);
            }
        });
        mineServiceTelTv.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + "18529067068");
            intent.setData(data);
            startActivity(intent);
        });
        mineSettingTv.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SettingActivity.class);
            startActivity(intent);
        });
        refreshLayout.setOnRefreshListener(() -> {
            initData();
            refreshLayout.setRefreshing(false);
        });
    }

    private void initData() {
        mPresenter.getUserInfo(0);

        if (MainApplication.Identity.equals(Common.ANSWER)) {
            scoreLl.setVisibility(View.GONE);
            mineBanner1Iv.setVisibility(View.GONE);
            mineBanner2Iv.setVisibility(View.GONE);
            mineSettingTv.setVisibility(View.VISIBLE);
            mineServiceTelTv.setVisibility(View.VISIBLE);
            feeDescriptionTv.setVisibility(View.GONE);
            mineAttentionTv.setVisibility(View.GONE);
        } else if (MainApplication.Identity.equals(Common.NORMAL)) {
            mineSettingTv.setVisibility(View.VISIBLE);
            mineServiceTelTv.setVisibility(View.GONE);
            feeDescriptionTv.setVisibility(View.GONE);
            mineAttentionTv.setVisibility(View.VISIBLE);
        }
        invitationCodeTv.setOnClickListener(v -> {
            if (userContentBean == null || userContentBean.getUserInfo() == null || userContentBean.getUserInfo().getIdentityCode() == null) {
                return;
            }
            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", userContentBean.getUserInfo().getIdentityCode());
            // 将ClipData内容放到系统剪贴板里
            cm.setPrimaryClip(mClipData);
            ToastUtil.show(getActivity() , "复制成功！");
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void userInfoResult(UserContentBean userContentBean, int type) {
        this.userContentBean = userContentBean;
        UserInfo userInfo = userContentBean.getUserInfo();
        GlideUtils.loadHeadImage(getActivity(), userInfo.getHeadPic(), mineHeadIv);
        invitationCodeTv.setText("我的邀请码：" + userContentBean.getUserInfo().getIdentityCode() + "（点击复制）");
        if (userInfo.getUserIdentity() == 2) {//老师
            mineNameTv.setText(CommonUtils.getStr(userInfo.getNickName()));
            String str = "";
            if (("1").equals(userInfo.getQualificationsId())) {
                str = "初级教师 ";
            } else if (("2").equals(userInfo.getQualificationsId())) {
                str = "中级教师 ";
            } else if (("2").equals(userInfo.getQualificationsId())) {
                str = "高级教师 ";
            }
            if (!TextUtils.isEmpty(userInfo.getMobile())) {
                str = str + userInfo.getMobile();
            }
            briefIntroductionTv.setText(str);
        } else {
            mineNameTv.setText(userInfo.getNickName() != null ? userInfo.getNickName() : "");
            String str = "";
            if (!TextUtils.isEmpty(userInfo.getGradeName())) {
                str = userInfo.getGradeName() + " ";
            }
            if (!TextUtils.isEmpty(userInfo.getMobile())) {
                str = str + userInfo.getMobile();
            }
            briefIntroductionTv.setText(str);
        }
        if (MainApplication.Identity.equals(Common.NORMAL)) {
            memberTv.setText(R.string.normal_member);
        } else {
            memberTv.setText(R.string.answer_people);
        }
        scoreTv.setText(getResources().getString(R.string.integral, userInfo.getIntegral() + ""));

        if (!TextUtils.isEmpty(userContentBean.getAudits()) && userContentBean.getAudits().trim().equals("1")) {
            // cutIv.setVisibility(View.VISIBLE);
            if (MainApplication.Identity.equals(Common.NORMAL)) {
                ToastUtil.show(getActivity(), "您的解答人申请已审核通过，请重新登录", Toast.LENGTH_LONG);
            }
        } else {
            cutIv.setVisibility(View.GONE);
        }

        if (type == 1) {
            if (userContentBean.getAudits() == null) {
                Intent intent = new Intent(getActivity(), MineDetailActivity.class);
                intent.putExtra(Common.USERINFO, userContentBean);
                intent.putExtra(Common.TYPE, Common.ApplyAnswer);
                startActivityForResult(intent, Common.MineDetailRequestCode);
            } else if (userContentBean.getAudits().equals(Common.AUDITS_SUCCESS)) {//审核通过
                ToastUtil.show(getActivity(), "您已经是解答人了！");
            } else {
                Intent intent = new Intent(getActivity(), ApplyResultActivity.class);
                intent.putExtra(Common.AUDITS, userContentBean.getAudits());
                intent.putExtra(Common.USERINFO, userContentBean);
                startActivityForResult(intent, Common.MineDetailRequestCode);
            }
        }
    }

    @Subscribe
    public void onEvent(MineEvent event) {
        mPresenter.getUserInfo(0);
    }

    @Override
    public void switchIdentity() {
        if (MainApplication.Identity.equals(Common.NORMAL)) {
            MainApplication.Identity = Common.ANSWER;
        } else {
            MainApplication.Identity = Common.NORMAL;
        }
        getActivity().finish();
        startActivity(MainActivity.class);
        EventBus.getDefault().post(new WebSocketEvent());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Common.MineDetailRequestCode && resultCode == Common.MineDetailResultCode) {
            mPresenter.getUserInfo(0);
        }
    }
}
